package com.store.app.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.bean.FreeBean;
import com.store.app.bean.PayBean;
import com.store.app.http.Stores;
import com.store.app.http.Submit;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.pay.alipay.Alipay;
import com.store.app.pay.alipay.AlipayModel;
import com.store.app.pay.alipay.AlipayState;
import com.store.app.utils.GoToLogin;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;
import com.store.app.wxapi.WXOrderbean;
import com.store.app.wxapi.WetchatPay;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 支付确认
 * 领了么订单支付页面
 */
public class ConfirmPaymentActivityForLLM extends BaseActivity implements AlipayState ,IOnHttpListener{
    //商品的bean
    private FreeBean bean;
    //购买数量
    private int num;
    //应付金额
    private String money;
    //title
    private TextView tv_title;
    //商品名
    private TextView tv_name;
    //商品数量
    private TextView tv_num;
    //商品价格
    private TextView tv_nomey;
    //提交
    private TextView tv_submit;
    //支付选择
    private RelativeLayout relat1, relat2, relat3,relat4;
    //账户余额
    private TextView tv_yuer;
    //支付选择imgview
    private ImageView img1, img2, img3,img4;
    //支付选择 1 余额 2支付宝 3微信
    private int pay_type = 2;
    //支付宝请求订单获取的model
    private AlipayModel model;
    private WXOrderbean wxOrderbean;
    private String dataStr;
    private EditText location;//收货地址
    private EditText tel_edit;//联系电话
    private String s_tel, s_location;
    private MyReceiver myReceiver;
    private boolean isedittouch = false;
    private boolean isedittouch_locat = false;
    private TextView tv_sum_money;//合计总价
    private TextView tv_ems_money;//需付邮费
    private EditText etStoreName;//店东姓名
    private TextView tvGold;//金币余额
    private TextView tv_sum_money_gold;
    private EditText etOrderMessage;//订单留言
    private GoToLogin goToLogin;
    private NetRequest netRequest;
    private String usable_cash_balance="0";//可用余额
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        goToLogin = new GoToLogin(this);

        if (getIntent() != null) {
            bean = (FreeBean) getIntent().getSerializableExtra("bean");
        }
        num = getIntent().getIntExtra("num", 0);
        Log.v("zyl","接受到num:"+num);
        money = getIntent().getStringExtra("money");
        setContentView(R.layout.activity_confirmpayment_ffl);
        initView();
        initData();
        initListeners();
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, new IntentFilter("FINISH"));
        netRequest= new NetRequest(this);
        netRequest.requestUsableCashBalanceFind(1);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
        EventBus.getDefault().unregister(this);//反注册EventBus
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //支付宝支付
                case 1:
                    new Alipay(ConfirmPaymentActivityForLLM.this,  model, ConfirmPaymentActivityForLLM.this).pay();
//                    new Alipay(ConfirmPaymentActivity.this, bean.getTitle(), bean.getDesc1(),"0.01", model,ConfirmPaymentActivity.this).pay();
                    break;
                //余额支付成功
                case 2:
                    dismissProgressDialog();
                    Toast.makeText(ConfirmPaymentActivityForLLM.this, "余额支付成功,订单已生成！", Toast.LENGTH_LONG).show();
//                    new QueryInfo().start();
                    netRequest.requestUsableCashBalanceFind(1);
                    goToOrder();
                    break;
                //刷新余额成功
                case 3:
                   // tv_yuer.setText(Stores.cash_balance + "");
                    break;
                //生成微信支付订单成功，调用给微信支付
                case 4:

//                    showToast("获取订单支付信息成功："+wxOrderbean.getAppid()+"dataStr:"+dataStr);
                    Log.v("zyl", "开启微信支付");

                    if (wxOrderbean != null) {
                        WetchatPay wetchatPay = new WetchatPay(ConfirmPaymentActivityForLLM.this, wxOrderbean);
                        wetchatPay.pay();
//                        showToast("实体不为空：" + wetchatPay.toString());
                    }
                    break;
                case 5:
                    showToast("微信支付失败,网络波动");
                    break;
                //金币支付
                case 6:
                    dismissProgressDialog();
                    Toast.makeText(ConfirmPaymentActivityForLLM.this, "金币支付成功,订单已生成！", Toast.LENGTH_LONG).show();
                    new QueryInfo().start();
                    goToOrder();
                    break;
                case 9:
                    showToast("微信支付失败,网络不通");
                    break;
                case 7:
                    dismissProgressDialog();
                    showToast("网络不通，支付失败");
                    break;
                //订单支付失败
                case 8:
                    dismissProgressDialog();
                    showToast(msg.obj.toString());
                    break;
            }
        }
    };

    private void goToOrder(){
        Intent intent2 = new Intent (ConfirmPaymentActivityForLLM.this,TheSingleOrderActivity.class);
        intent2.putExtra("showFragmentIndex", "2");
        intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent2);
        finish();
    }

    @Override
    public void finish() {
        dismissProgressDialog();
        super.finish();
    }

    private void initListeners() {
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                if (pay_type == 1) {
                    if (!MoneyUtil.moneyComp(usable_cash_balance + "", tv_sum_money.getText().toString())) {
                        Toast.makeText(ConfirmPaymentActivityForLLM.this, "可用零钱余额不足,请选择其他支付方式！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    s_tel = tel_edit.getText().toString();
                    if (TextUtils.isEmpty(s_tel)) {
                        Toast.makeText(ConfirmPaymentActivityForLLM.this, "请输入收货人的联系电话！", Toast.LENGTH_SHORT).show();
                        return;
                    }
//                    if (!Pattern.compile("(\\d{11})|(\\+\\d{3,})").matcher(s_tel).matches()) {
//                        Toast.makeText(ConfirmPaymentActivity.this, "请输入正确的收货人的联系电话！", Toast.LENGTH_SHORT).show();
//                        return;
//                    }
                    s_location = location.getText().toString();
                    if (TextUtils.isEmpty(s_location)) {
                        Toast.makeText(ConfirmPaymentActivityForLLM.this, "请输入收货人的地址！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (s_location.length() > 200) {
                        Toast.makeText(ConfirmPaymentActivityForLLM.this, "收货人的地址字数过多！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    showConfirmDialog("", "是否确定支付"+ tv_sum_money.getText().toString()+"元 ?", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showProgressDialog("","支付中...",true);
                            Log.v("zyl","支付中");
                            new GetOrder(tv_sum_money.getText().toString(), SettingData.PAYMENT_WAY_05).start();
                        }
                    });

                } else if (pay_type == 2) {
                    //支付宝的支付方式 ZFFS_01
                    s_tel = tel_edit.getText().toString();
                    if (TextUtils.isEmpty(s_tel)) {
                        Toast.makeText(ConfirmPaymentActivityForLLM.this, "请输入收货人的联系电话！", Toast.LENGTH_SHORT).show();
                        return;
                    }
//                    if (!Pattern.compile("(\\d{11})|(\\+\\d{3,})").matcher(s_tel).matches()) {
//                        Toast.makeText(ConfirmPaymentActivity.this, "请输入正确的收货人的联系电话！", Toast.LENGTH_SHORT).show();
//                        return;
//                    }
                    s_location = location.getText().toString();
                    if (TextUtils.isEmpty(s_location)) {
                        Toast.makeText(ConfirmPaymentActivityForLLM.this, "请输入收货人的地址！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (s_location.length() > 200) {
                        Toast.makeText(ConfirmPaymentActivityForLLM.this, "收货人的地址字数过多！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    new GetOrder(MoneyUtil.formatMoney(tv_sum_money.getText().toString()), SettingData.PAYMENT_WAY_01).start();
                } else if (pay_type == 3) {
                    //微信支付
                    s_tel = tel_edit.getText().toString();
                    if (TextUtils.isEmpty(s_tel)) {
                        Toast.makeText(ConfirmPaymentActivityForLLM.this, "请输入收货人的联系电话！", Toast.LENGTH_SHORT).show();
                        return;
                    }
//                    if (!Pattern.compile("(\\d{11})|(\\+\\d{3,})").matcher(s_tel).matches()) {
//                        Toast.makeText(ConfirmPaymentActivity.this, "请输入正确的收货人的联系电话！", Toast.LENGTH_SHORT).show();
//                        return;
//                    }

                    s_location = location.getText().toString();
                    if (TextUtils.isEmpty(s_location)) {
                        Toast.makeText(ConfirmPaymentActivityForLLM.this, "请输入收货人的地址！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (s_location.length() > 200) {
                        Toast.makeText(ConfirmPaymentActivityForLLM.this, "收货人的地址字数过多！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    boolean ifInstall = Utils.isWXAppInstalledAndSupported(ConfirmPaymentActivityForLLM.this);
                    if (ifInstall) {

                        new GetOrderWX(MoneyUtil.formatMoney(tv_sum_money.getText().toString()), SettingData.PAYMENT_WAY_02).start();
                    } else {
                        showToast("尚未安装微信,请检查您的手机");
                        return;
                    }

                }else if(pay_type==4){
                    Log.v("zyl","金币余额："+Stores.gold);
                    Log.v("zyl","需支付的价格："+tv_sum_money.getText().toString());
                    Log.v("zyl","需支付的金币："+MoneyUtil.moneyMul(tv_sum_money.getText().toString(), "100"));

                    if (!MoneyUtil.moneyComp(Stores.gold + "", MoneyUtil.moneyMul(tv_sum_money.getText().toString(),"100"))) {
                        Toast.makeText(ConfirmPaymentActivityForLLM.this, "金币余额不足,请选择其他支付方式！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    s_tel = tel_edit.getText().toString();
                    if (TextUtils.isEmpty(s_tel)) {
                        Toast.makeText(ConfirmPaymentActivityForLLM.this, "请输入收货人的联系电话！", Toast.LENGTH_SHORT).show();
                        return;
                    }
//                    if (!Pattern.compile("(\\d{11})|(\\+\\d{3,})").matcher(s_tel).matches()) {
//                        Toast.makeText(ConfirmPaymentActivity.this, "请输入正确的收货人的联系电话！", Toast.LENGTH_SHORT).show();
//                        return;
//                    }
                    s_location = location.getText().toString();
                    if (TextUtils.isEmpty(s_location)) {
                        Toast.makeText(ConfirmPaymentActivityForLLM.this, "请输入收货人的地址！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (s_location.length() > 200) {
                        Toast.makeText(ConfirmPaymentActivityForLLM.this, "收货人的地址字数过多！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String goldStr = "";
                    try{
                        goldStr = MoneyUtil.moneyMul(tv_sum_money.getText().toString(), "100");
                        double goldDouble = Double.parseDouble(goldStr);
                         goldStr = (int)goldDouble+"";
                    }catch (Exception e){
                        goldStr=(MoneyUtil.moneyMul(tv_sum_money.getText().toString(),"100"));
                        e.printStackTrace();
                    }
                    showConfirmDialog("", "是否确定支付"+goldStr+"金币 ?", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showProgressDialog("","支付中...",true);
                            new GetOrder(MoneyUtil.moneyMul(tv_sum_money.getText().toString(),"100"), SettingData.PAYMENT_WAY_08).start();
                        }
                    });
                }
            }
        });
        findViewById(R.id.public_ll_return).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        relat1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 1;
                img1.setBackgroundResource(R.drawable.pay_circle);
                img2.setBackgroundResource(R.drawable.pay_circle_gray);
                img3.setBackgroundResource(R.drawable.pay_circle_gray);
                img4.setBackgroundResource(R.drawable.pay_circle_gray);

            }
        });
        relat2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 2;
                img1.setBackgroundResource(R.drawable.pay_circle_gray);
                img2.setBackgroundResource(R.drawable.pay_circle);
                img3.setBackgroundResource(R.drawable.pay_circle_gray);
                img4.setBackgroundResource(R.drawable.pay_circle_gray);
            }
        });
        relat3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 3;
                img1.setBackgroundResource(R.drawable.pay_circle_gray);
                img2.setBackgroundResource(R.drawable.pay_circle_gray);
                img3.setBackgroundResource(R.drawable.pay_circle);
                img4.setBackgroundResource(R.drawable.pay_circle_gray);
            }
        });
        relat4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 4;
                img4.setBackgroundResource(R.drawable.pay_circle);
                img1.setBackgroundResource(R.drawable.pay_circle_gray);
                img2.setBackgroundResource(R.drawable.pay_circle_gray);
                img3.setBackgroundResource(R.drawable.pay_circle_gray);
            }
        });

    }

    private void initData() {
                Log.v("zyl","init  Stores.address:"+ Stores.address);
                Log.v("zyl","init  Stores.area_desc:"+ Stores.area_desc);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        if(TextUtils.isEmpty(Stores.address)) {
            Stores.address = preferences.getString("address", "");
        }
        if(TextUtils.isEmpty(Stores.area_desc)) {
            Stores.area_desc = preferences.getString("area_desc", "");
        }
        String s_title = bean.getItem_goods_title();
        if (!TextUtils.isEmpty(s_title)) {
            tv_name.setText(s_title);
        }

        String sumMoney = MoneyUtil.moneyAdd(money,"0");
        tv_sum_money.setText(sumMoney);

        tv_nomey.setText(money);
        tv_title.setText("确认支付");
        String s_yuer = Stores.cash_balance + "";
//        if (!TextUtils.isEmpty(s_yuer)) {
//            tv_yuer.setText(s_yuer);
//        }
        String s_gold = Stores.gold;//金币余额
        if(!TextUtils.isEmpty(s_gold)){
            tvGold.setText(s_gold);
        }
        if(!TextUtils.isEmpty(Stores.contact_person)){
            etStoreName.setText(Stores.contact_person);
        }
        location.setEnabled(false);
        tel_edit.setEnabled(false);
        etStoreName.setEnabled(false);
        if (!TextUtils.isEmpty(Stores.contact_tel)) {
            tel_edit.setText(Stores.contact_tel);
        }

        tv_num.setText(num + "");
        if (!TextUtils.isEmpty(Stores.address)&&!TextUtils.isEmpty(Stores.area_desc)) {
            location.setText(Stores.area_desc+Stores.address);
        }
//        if(!TextUtils.isEmpty(Stores.address)){
//            location.setText(Stores.address);
//            location.setCursorVisible(false);
//            isedittouch_locat=true;
//        }
//        location.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if(isedittouch_locat){
//                    location.setCursorVisible(true);
//                    isedittouch_locat=false;}
//                return false;
//            }
//        });
//        if(!TextUtils.isEmpty(Stores.contact_tel)){
//            tel_edit.setText(Stores.contact_tel);
//            tel_edit.setCursorVisible(false);
//            isedittouch=true;
//        }
//        tel_edit.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if(isedittouch){
//                tel_edit.setCursorVisible(true);
//                isedittouch=false;}
//                return false;
//            }
//        });
    }

    public void onEvent(PayBean event) {
        if (event.type == 2) {
            //跳转到订单页面
          goToOrder();
        }
    }

    private void initView() {
        etOrderMessage = (EditText) findViewById(R.id.et_order_message);
        tv_title = (TextView) findViewById(R.id.tvTitle);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_num = (TextView) findViewById(R.id.tv_num);
        tv_nomey = (TextView) findViewById(R.id.tv_money);
        tv_submit = (TextView) findViewById(R.id.submit);
        relat1 = (RelativeLayout) findViewById(R.id.pay_relat1);
        relat2 = (RelativeLayout) findViewById(R.id.pay_relat2);
        relat3 = (RelativeLayout) findViewById(R.id.pay_relat3);
        relat4 = (RelativeLayout) findViewById(R.id.pay_relat4);
        tv_yuer = (TextView) findViewById(R.id.yuer);
        tvGold = (TextView) findViewById(R.id.tv_gold);
        img1 = (ImageView) findViewById(R.id.pay_check_1);
        img2 = (ImageView) findViewById(R.id.pay_check_2);
        img3 = (ImageView) findViewById(R.id.pay_check_3);
        img4 = (ImageView) findViewById(R.id.pay_check_4);
        location = (EditText) findViewById(R.id.tv_location);
        tel_edit = (EditText) findViewById(R.id.compay_edit_tel);
        tv_sum_money = (TextView) findViewById(R.id.tv_sum_money);
        tv_sum_money_gold = (TextView) findViewById(R.id.tv_sum_money_gold);
        tv_ems_money = (TextView) findViewById(R.id.tv_ems_money);
        etStoreName = (EditText) findViewById(R.id.etStoreName);

        EventBus.getDefault().register(this);
    }

    @Override
    public void onAlipaySuccess() {
        Log.v("zyl", "支付宝支付成功");
        Toast.makeText(ConfirmPaymentActivityForLLM.this, "支付成功,订单已生成", Toast.LENGTH_SHORT).show();
        goToOrder();
    }

    @Override
    public void onAlipayFail() {
        Log.v("zyl", "支付宝支付失败");
    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        //可用资产
        if(requestId ==1){
            try {
                JSONObject jsonObject = new JSONObject(result);
                usable_cash_balance = jsonObject.getString("usable_cash_balance");
                Log.v("zyl","设置可用金额："+usable_cash_balance);
                tv_yuer.setText(usable_cash_balance);
            }catch (Exception e ){}
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        if(requestId == 1){
            ToastTools.showShort(this,msg);
        }
    }

    /**
     * 订单支付接口
     */
    public class GetOrder extends Thread {
        //现金
        String total_priceser;
        private String payWay;

        public GetOrder(String total_priceser, String payWay) {
            this.total_priceser = total_priceser;
            this.payWay = payWay;
        }

        public void run() {
            try {
                JSONObject params = new JSONObject();
                params.put("amount", total_priceser + "");    //金额
                params.put("buyer_id", MainActivity.member_id);                 //店东的id
                params.put("seller_id", SettingData.default_seller_id);         //每天惠的id
                params.put("data_source","SJLY_02");
                params.put("order_type_key", SettingData.DDLX_07);
                params.put("detail", "领了么");

                Log.v("zyl", "total_priceser:" + total_priceser);
                //支付宝支付方式  "ZFFS_01"
                params.put("payment_way_key", payWay);                          //支付方式
                //订单信息（包含邮费）
                JSONObject paramsOrder= new JSONObject();


                paramsOrder.put("remark", etOrderMessage.getText().toString().trim()+"");
                paramsOrder.put("data_source", SettingData.DATA_SOURCE_MTH);
                paramsOrder.put("order_id", bean.getOrder_id());
                paramsOrder.put("payment_way_key", payWay);
                paramsOrder.put("delivery_address", s_location);
                paramsOrder.put("contact_person", Stores.contact_person);
                paramsOrder.put("contact_tel", s_tel);
                params.put("out_trade_body", paramsOrder.toString());
                List<NameValuePair> pairList = new ArrayList<NameValuePair>();

                pairList.add(new BasicNameValuePair("params", params.toString()));
                pairList.add(new BasicNameValuePair("service", "finance.orderPay"));
                pairList.add(new BasicNameValuePair("user_token", MainActivity.user_token));
                String sign = Submit.genPackageSignUser(pairList);
                pairList.add(new BasicNameValuePair("sign", sign));

                JSONObject obj = Submit.submit(pairList, Stores.http + "/openapi/finance");
                String rsp_code = obj.getString("rsp_code");

                if (rsp_code.equals("succ")) {
                    dataStr = obj.getString("data");
                    Log.v("zyl", "订单支付成功:" + dataStr);
                    if (payWay.equals(SettingData.PAYMENT_WAY_01)) {
                        model = new AlipayModel();
                        model.json2Model(dataStr);
                        handler.sendEmptyMessage(1);
                    } else if (payWay.equals(SettingData.PAYMENT_WAY_05)) {
                        handler.sendEmptyMessage(2);
                    }else if(payWay.equals(SettingData.PAYMENT_WAY_08)){
                        handler.sendEmptyMessage(6);
                    }
                } else {
                    String errorMsg = obj.getString("error_msg");
                    Message msg = Message.obtain();
                    msg.what = 8;
                    msg.obj = errorMsg;
                    if(errorMsg.contains("token")){
                        goToLogin.setGoToLogin();
                    }else{
                        handler.sendMessage(msg);
                    }
                    Log.v("zyl", "订单支付失败:" + obj.getString("error_msg"));
                }
            } catch (Exception e) {
                handler.sendEmptyMessage(7);
                e.printStackTrace();
            }
        }
    }




    /**
     * 微信订单支付
     */
    public class GetOrderWX extends Thread {
        //现金
        String total_priceser;
        private String payWay;

        public GetOrderWX(String total_priceser, String payWay) {
            this.total_priceser = total_priceser;
            this.payWay = payWay;
        }

        public void run() {
            try {

                JSONObject params = new JSONObject();
                params.put("amount", total_priceser + "");    //金额
                params.put("buyer_id", MainActivity.member_id);                 //店东的id
                params.put("seller_id", SettingData.default_seller_id);         //每天惠的id
                params.put("data_source","SJLY_02");
                params.put("order_type_key", SettingData.DDLX_07);
                params.put("detail", "领了么");
                Log.v("zyl", "total_priceser:" + total_priceser);
                //支付宝支付方式  "ZFFS_01"
                params.put("payment_way_key", payWay);                          //支付方式
                //订单信息（包含邮费）
                JSONObject paramsOrder= new JSONObject();
                paramsOrder.put("remark", etOrderMessage.getText().toString().trim()+"");
                paramsOrder.put("data_source", SettingData.DATA_SOURCE_MTH);
                paramsOrder.put("order_id", bean.getOrder_id());
                paramsOrder.put("payment_way_key", payWay);
                paramsOrder.put("delivery_address", s_location);
                paramsOrder.put("contact_person", Stores.contact_person);
                paramsOrder.put("contact_tel", s_tel);
                params.put("out_trade_body", paramsOrder.toString());
                Log.i("mylog", paramsOrder.toString());
                List<NameValuePair> pairList = new ArrayList<NameValuePair>();

                pairList.add(new BasicNameValuePair("params", params.toString()));
                pairList.add(new BasicNameValuePair("service", "finance.orderPay"));
                pairList.add(new BasicNameValuePair("user_token", MainActivity.user_token));
                String sign = Submit.genPackageSignUser(pairList);
                pairList.add(new BasicNameValuePair("sign", sign));

                JSONObject obj = Submit.submit(pairList, Stores.http + "/openapi/finance");
                String rsp_code = obj.getString("rsp_code");

                if (rsp_code.equals("succ")) {
                    dataStr = obj.getString("data");
                    JSONObject jsonObject = new JSONObject(dataStr);
                    Log.v("zyl", "微信生成订单成功:" + dataStr);
                    wxOrderbean = new WXOrderbean();
                    wxOrderbean.setTransaction_no(jsonObject.getString("transaction_no"));
                    wxOrderbean.setTimestamp(jsonObject.getString("timestamp"));
                    wxOrderbean.setSign(jsonObject.getString("sign"));
                    wxOrderbean.setPartnerid(jsonObject.getString("partnerid"));
                    wxOrderbean.setPackageX(jsonObject.getString("package"));
                    wxOrderbean.setNoncestr(jsonObject.getString("noncestr"));
                    wxOrderbean.setAppid(jsonObject.getString("appid"));
                    wxOrderbean.setPrepayid(jsonObject.getString("prepayid"));


////                    Gson gson = new Gson();
//                    w
////                     wxOrderbean = gson.fromJson(dataStr, WXOrderbean.class);

                    handler.sendEmptyMessage(4);
                } else {
                    Log.v("zyl", "微信订单支付失败:"+obj.getString("error_msg"));
                    if(goToLogin.setGoToLogin(obj)){

                    }else {
                        handler.sendEmptyMessage(5);
                    }

                }
            } catch (Exception e) {
                handler.sendEmptyMessage(9);
                e.printStackTrace();

                Log.v("zyl", "微信订单支付失败，网络异常:", e);
            }
        }
    }

    public class QueryInfo extends Thread {
        public QueryInfo() {

        }

        public void run() {
            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("app_token",
                        MainActivity.app_token));
                JSONObject paramsone = new JSONObject();
//						paramsone.put("member_id", MainActivity.member_id);
                paramsone.put("member_id", MainActivity.member_id + "");
                params.add(new BasicNameValuePair("params", paramsone
                        .toString()));
                params.add(new BasicNameValuePair("service",
                        "finance.memberAssetFind"));
                String sign = Submit.genPackageSign(params);
                params.add(new BasicNameValuePair("sign", sign));
                JSONObject obj = Submit.submit(params, Stores.http + "/openapi/finance");

                String result = obj.getString("rsp_code");
                if (result.equals("succ")) {
                    Log.v("zyl", "查询余额信息成功:" + obj.getString("data"));
                    JSONObject jsonObject = new JSONObject(obj.getString("data"));
                    int vo = Integer.parseInt(jsonObject.getString("voucher_balance"));
                    double banlance = Double.parseDouble(jsonObject.getString("cash_balance"));
                    Stores.cash_balance = banlance;
                    Stores.voucher_balance = vo;
                    Stores.gold = jsonObject.getString("gold");
                    Log.v("zyl", "查询到的金币：" + Stores.gold);
                    Log.v("zyl", "Stores.voucher_balance:" + Stores.voucher_balance);
                    handler.sendEmptyMessage(3);
                } else {
                    if(goToLogin.setGoToLogin(obj)){

                    }
                    Log.v("zyl", "查询余额信息失败");
                }
            } catch (Exception e) {
                Log.v("zyl", "网络不通");
            }

        }
    }

    /**
     * 微信支付成功之后发送一个广播过来关闭页面
     */
    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.v("zyl", "接收到广播");
            Toast.makeText(ConfirmPaymentActivityForLLM.this, "支付成功,订单已生成", Toast.LENGTH_LONG).show();
            goToOrder();
            finish();
        }
    }
}
